package generator;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {

	public static final void main(String[] args) throws IOException {
		Map<String, List<String[]>> data = readFile(new File("data.csv"), "utf-8");
		// Map<String, List<String[]>> data = readFile(new File("data.csv"), "euc-kr");
		// Map<String, List<String[]>> data = readFile(new File("data.csv"), "sjis");
		for (String clazz : data.keySet()) {
			String[] array = data.get(clazz).get(0);
			Director d = new Director(new ParcelableBuilder());
			// Director d = new Director(new SetterGetterBuilder());
			d.setData(clazz, array[1], data.get(clazz));
			String source = d.create();
			writeFile(clazz, source);
		}
	}

	private static final Map<String, List<String[]>> readFile(File file, String charsetName) throws IOException {
		HashMap<String, List<String[]>> all = new HashMap<String, List<String[]>>();
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetName));
		String line;
		String clazz = null;
		String description = null;
		boolean first = true;
		while ((line = br.readLine()) != null) {
			if (first) {
				first = false;
				continue;
			}

			if (!line.isEmpty()) {
				line = line.replaceAll("\"", "");
				String[] array = line.split(",");

				if (array[0] != null && array[0].length() > 0) {
					clazz = array[0];
				}

				if (array[1] != null && array[1].length() > 0) {
					description = array[1];
				}

				if (clazz == null
						|| description == null
						|| array.length < 6
						|| array.length > 7) {
					throw new IllegalArgumentException("Invalid class info:" + line);
				} else {
					array[0] = clazz;
					array[1] = description;
				}

				if (all.get(clazz) != null) {
					all.get(clazz).add(array);
				} else {
					List<String[]> data = new ArrayList<String[]>();
					data.add(array);
					all.put(clazz, data);
				}
			}
		}
		br.close();
		return all;
	}

	private static final void writeFile(String name, String source) throws IOException {
		File dir = new File("./src/");
		if (!dir.exists()) {
			dir.mkdirs();
		}

		String className = name;
		int dot = name.lastIndexOf(".");
		if (dot != -1) {
			className = name.substring(dot + 1);
			name = name.replaceAll("[.]", "/");
			dir = new File(dir, name.substring(0, dot));
			if (!dir.exists()) {
				dir.mkdirs();
			}
		}

		BufferedWriter bw = new BufferedWriter(new FileWriter(new File(dir, className + ".java")));
		bw.write(source);
		bw.flush();
		bw.close();
	}
}
